﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.Serialization.Json;

namespace CommunitySystem.Model.Silverlight
{
    public class EntityConvertor
    {
        /// <summary>
        /// 通过json方式将实体之间转换
        /// </summary>
        /// <typeparam name="T">目标实体</typeparam>
        /// <param name="entity">转换实体</param>
        /// <returns></returns>
        public static T Convert<T>(object entity) where T: new()
        {
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(entity.GetType());
            ser.WriteObject(ms, entity);
            byte[] json = ms.ToArray();
            T p2 = new T();
            if (p2 is DataEntity)
            {
                (p2 as DataEntity).IsValidate = false;
            }
            using (MemoryStream ms2 = new System.IO.MemoryStream(json))
            {
                ms2.Read(json, 0, json.Length);
                DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(T));
                p2 = (T)ser2.ReadObject(ms2);
                DataEntity de = p2 as DataEntity;
                if (de != null)
                {
                    de.IsValidate = true;
                }
                return p2;                 
            }
            return p2;
        }


    }
}
